/****************************************************************************
 * 2025.5 GRAVEROBBER-PC
 ****************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using QAssetBundle;
using UnityEngine;
using UnityEngine.UI;
using QFramework;
using Unity.VisualScripting;

namespace ProjectSurvival
{
    public partial class CoinUpgradePanel : UIElement, IController
    {
        private void Awake()
        {
           
            CoinUpgradeItremRoot.DestroyChildren();
            foreach (var coinUpgradeItem in this.GetSystem<CoinUpgradeSystem>().CoinUpgradeItems
                         .Where((item) => !item.UpgradeFinish))
            {
                var item = btnUpgradeTemplate.InstantiateWithParent(this.CoinUpgradeItremRoot);
                var coinCache = coinUpgradeItem;
                item.transform.Find("btnText").GetComponent<Text>().text =
                    $"{coinCache.Description} {coinCache.Price}金币";
                //注册升级状态变更事件,如果满足条件则显示，不满足则隐藏
                coinCache.OnItemUpgrandeChanged.Register(() =>
                {
                    if (coinCache.ConditionCheck())
                    {
                        item.Show();
                    }
                    else
                    {
                        item.Hide();
                    }
                }).UnRegisterWhenGameObjectDestroyed(item);

                if (coinCache.ConditionCheck())
                {
                    item.Show();
                }
                else
                {
                    item.Hide();
                }
                //判断当前金币是否够消费，如果不够则变为不可点击
                Global.Coin.RegisterWithInitValue((coinCount) =>
                {
                    if (coinCount >= coinCache.Price)
                    {
                        item.interactable = true;
                    }
                    else
                    {
                        item.interactable = false;
                    }
                }).UnRegisterWhenGameObjectDestroyed(gameObject);

                item.GetComponent<Button>().onClick.AddListener(() =>
                {
                    AudioKit.PlaySound(Buttonclick_wav.ButtonClick);
                    coinCache.Upgrade();
                    AudioKit.PlaySound("AbilityLevelUp");
                });
            }
            
            Global.Coin.RegisterWithInitValue((CoinCOunt) => { coinCountText.text = $"金币：{CoinCOunt}"; })
                .UnRegisterWhenGameObjectDestroyed(gameObject);

            btnClose.onClick.AddListener(() =>
            {
                AudioKit.PlaySound(Buttonclick_wav.ButtonClick);
                this.Hide();
            });
        }

        protected override void OnBeforeDestroy()
        {
        }

        public IArchitecture GetArchitecture()
        {
            return Global.Interface;
        }
    }
}